package com.example.app;

import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.squareup.picasso.Picasso;
import org.jetbrains.annotations.NotNull;

import java.util.List;
import java.util.Objects;

public class NewsItemAdapter extends RecyclerView.Adapter<NewsItemAdapter.ViewHolder> {
    private final List<NewsItem> newsItemList;

    static class ViewHolder extends RecyclerView.ViewHolder {
        View news;
        TextView name;
        TextView author;
        TextView time;
        ImageView pic;

        public ViewHolder(View view) {
            super(view);
            news = view;
            name = view.findViewById(R.id.news_name);
            author = view.findViewById(R.id.news_author);
            time = view.findViewById(R.id.news_time);
            pic = view.findViewById(R.id.news_pic);
        }
    }

    public NewsItemAdapter(List<NewsItem> newsItemList) {
        this.newsItemList = newsItemList;
    }

    @NotNull
    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.news_item, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        final NewsItem item = newsItemList.get(position);
        holder.name.setText(item.name);
        holder.author.setText(item.author);
        holder.time.setText(item.time);
        if (Objects.equals(item.pic, ""))
            holder.pic.setImageResource(R.drawable.no_news_page);
        else
            Picasso.get().load(item.pic).into(holder.pic);

        holder.news.setOnClickListener(view -> {
            Context context = view.getContext();
            Intent intent = new Intent(context, WebpageActivity.class);
            // 将属性传递给WebpageActivity
            intent.putExtra("name", item.name);
            intent.putExtra("url", item.url);
            // 启动活动
            context.startActivity(intent);
        });
    }

    @Override
    public int getItemCount() {
        return newsItemList.size();
    }
}

